package middleware

import (
	"fmt"
	"net/http"
	"runtime/debug"

	"github.com/gin-gonic/gin"
)

// ErrorResponse 定义API错误响应格式
type ErrorResponse struct {
	Code    int    `json:"code"`    // 错误码
	Message string `json:"message"` // 错误信息
	Details string `json:"details"` // 错误详情(可选)
}

// RecoveryMiddleware 全局错误处理中间件
func RecoveryMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		defer func() {
			if err := recover(); err != nil {
				// 获取堆栈信息
				stack := debug.Stack()

				// 记录错误日志
				fmt.Printf("Panic recovered: %v\nStack trace: %s\n", err, stack)

				// 统一错误响应
				c.AbortWithStatusJSON(http.StatusInternalServerError, ErrorResponse{
					Code:    http.StatusInternalServerError,
					Message: "服务器内部错误",
					Details: fmt.Sprintf("%v", err),
				})
			}
		}()

		c.Next()

		// 处理普通错误
		if len(c.Errors) > 0 {
			err := c.Errors.Last()
			c.AbortWithStatusJSON(http.StatusInternalServerError, ErrorResponse{
				Code:    http.StatusInternalServerError,
				Message: "请求处理失败",
				Details: err.Error(),
			})
		}
	}
}
